package com.adingxiong.security.springsecurity.service;

import com.adingxiong.security.springsecurity.entity.MyUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName UserDetails
 * @Description TODO
 * @Author xiongchao
 * @Date 2020/10/16 9:13
 **/
@Configuration
public class UserDetailService implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        MyUser user = new MyUser();
        user.setUsername(s);
        user.setPasssword(passwordEncoder.encode("123456"));
        System.out.println("encode password : " + passwordEncoder.encode("123456"));
        List<GrantedAuthority> authorities = new ArrayList<>();
        if("user".equalsIgnoreCase(s)){
            authorities = AuthorityUtils.commaSeparatedStringToAuthorityList("admin");
        }else {
            authorities = AuthorityUtils.commaSeparatedStringToAuthorityList("test");
        }
        return new User(s,user.getPasssword(),user.isEnable(),user.isAccoutNonExpire(),user.isCredentialsNonExpired(),user.isAccoutNoLock(),
                authorities  );
    }
}
